package com.witmed.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class FileDownloadServlet
 */
@WebServlet("/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 读取指定服务器中的文件
		// 存储图片的文件目录
		String root = "E:\\fileupload\\Images\\";
		
		// 获取指定的文件名
		String fileName = request.getParameter("fileName"); // 1.jpg
		
		// 文件的完整路径
		StringBuffer path = new StringBuffer();
		path.append(root).append(fileName);   // E:\\fileupload\\images\\1.jpg
		
		// 关联文件
		File file = new File(path.toString());
		
		// 通过字节流输入流 读取
		FileInputStream fis = new FileInputStream(file);
		
		// 通过字节数组输出流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		// 边读边写
		while ( (n = fis.read(b)) != -1 ) { // 有数据可读
			
			// 写
			bos.write(b,0,n);
		}
		
		fis.close();
		
		// 通过servlet输出流将文件以字节数组的形式输出到网页中
		ServletOutputStream sos = response.getOutputStream();
		sos.write(bos.toByteArray());
		
	}

}
